<?php
namespace app\store\controller\user;

use app\store\controller\Controller;
use app\store\model\user\Sn as SnModel;

/**
 * 设备sn码控制器
 * Class Sn
 * @package app\store\controller\user
 */
class Sn extends Controller
{
    /**
     * 设备SN码列表
     * @param string $search
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index($search = '')
    {
        $model = new SnModel;
        return $this->fetch('index', [
            'list' => $model->getList($search),
        ]);
    }

    /**
     * 添加设备SN
     * @return array|mixed
     */
    public function add()
    {
        $model = new SnModel;
        if (!$this->request->isAjax()) {
            return $this->fetch('add');
        }
        // 新增记录
        if ($model->addSn($this->postData('sn'))) {
            return $this->renderSuccess('添加成功', url('user.sn/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 更新SN码
     * @param $id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function edit($id)
    {
        // SN码详情
        $model = SnModel::detail($id);
        if (!$this->request->isAjax()) {
            return $this->fetch('edit', compact('model'));
        }
        // 更新记录
        if ($model->edit($this->postData('sn'))) {
            return $this->renderSuccess('更新成功', url('user.sn/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 删除
     * @param $id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete($id)
    {
        // 商品详情
        $model = SnModel::detail($id);
        if (!$model->setDelete()) {
            return $this->renderError('删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

}